import { FC, ReactNode, useCallback } from "react";
import { CompProps, FormItemChildProps } from "../../types/comp";
import Upload from "../upload";
import { Button, Card } from "antd";
import CheckImgList from "../CheckImgList";
import CardWrap from "./CardWrap";

const ImageListUpload: FC<
  FormItemChildProps & {
    addLabel?: string;
    onClick?: (data?: any, idx?: number) => void;
    onDelete?: (data: any, idx: number) => void;
    labelAtr?: string;
    sourceAtr?: string;
    btnNode?: ReactNode;
    createItem?: (v: string) => any;
  }
> = ({
  addLabel,
  createItem = (v) => v,
  value,
  onClick,
  onDelete,
  sourceAtr = "media_url",
  labelAtr,
  onChange,
  btnNode,
}) => {
  const Wrapper = useCallback<FC<CompProps>>(
    ({ children }) => {
      if (onClick) {
        return <>{children}</>;
      }
      return (
        <Upload
          onChange={async (v: string) => {
            onChange?.([...value, await createItem(v)]);
          }}
          itemRender={(v) => null}
        >
          {children}
        </Upload>
      );
    },
    [onClick, onChange]
  );
  return (
    <CardWrap>
      {btnNode ? (
        btnNode
      ) : (
        <Wrapper>
          <Button type="primary" size="small" onClick={() => onClick?.()}>
            {addLabel}
          </Button>
        </Wrapper>
      )}
      <CheckImgList
        size={120}
        onModify={onClick}
        onDelete={onDelete}
        labelAtr={labelAtr}
        value={value}
        sourceAtr={sourceAtr}
      />
    </CardWrap>
  );
};

export default ImageListUpload;
